import puppeteer from 'puppeteer-core';
import { Inject, Injectable } from '@nestjs/common';
import { LogService } from '../log/log.service';

@Injectable()
export class SpiderService {
  @Inject(LogService)
  private readonly logger: LogService;

  async spiderBaiduAi(word: string, maxRetries: number = 3, solveContent: (html: string) => string) {
    let attempt = 0;

    while (attempt < maxRetries) {
      attempt++;
      const message = `${word}：第${attempt}次尝试执行`;
      this.logger.info(message);

      const browser = await puppeteer.launch({
        executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe',
        headless: true,
        args: [
          '--no-sandbox',
          '--disable-setuid-sandbox',
          '--disable-dev-shm-usage',
          '--disable-accelerated-2d-canvas',
          '--no-first-run',
          '--no-zygote',
          '--disable-gpu',
        ],
      });
      const page = await browser.newPage();

      // 设置 User-Agent 模拟真实浏览器
      await page.setUserAgent(
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      );

      // 设置其他浏览器特征
      await page.setViewport({ width: 1366, height: 768 });
      await page.setExtraHTTPHeaders({
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
      });

      try {
        // 访问网站
        await page.goto(`https://chat.baidu.com/search?word=${word}`, {
          waitUntil: 'networkidle2',
          timeout: 4 * 60 * 1000,
        });

        // 获取页面标题
        const title = await page.title();
        const titleMessage = `✅ 页面标题: ${title}`;
        this.logger.info(titleMessage);

        // 等待30秒
        await page.waitForSelector('div[data-module="ai_questionClosely"]', {
          timeout: 4 * 60 * 1000,
        });

        // 获取页面HTML
        const html = await page.content();
        const content = solveContent(html);

        await browser.close();

        // 如果成功获取到内容，直接返回
        if (content && content.length > 0) {
          const successMessage = `${word}：第${attempt}次尝试成功`;
          this.logger.info(successMessage);
          return content;
        } else {
          throw new Error('未获取到有效内容');
        }
      } catch (error) {
        const errorMessage = `第${attempt}次尝试失败: ${error.message}`;
        this.logger.error(errorMessage);
        await browser.close();

        // 如果不是最后一次尝试，等待一段时间再重试
        if (attempt < maxRetries) {
          const retryMessage = `等待2秒后进行第${attempt + 1}次重试...`;
          this.logger.info(retryMessage);
          await new Promise((resolve) => setTimeout(resolve, 2000));
        }
      }
    }

    const finalMessage = `${word}：所有${maxRetries}次尝试都失败了`;
    this.logger.error(finalMessage);
    return '';
  }
}
